﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kz.Telegram.Bot.Infrastructure.Helpers
{
    public class FileHelper
    {
        public static void DeleteFile(string fileFullPath)
        {
            try
            {
                if (File.Exists(fileFullPath) || Directory.Exists(fileFullPath))
                {
                    FileAttributes attr = File.GetAttributes(fileFullPath);

                    if (attr == FileAttributes.Directory)
                    {
                        Directory.Delete(fileFullPath, true);
                    }
                    else
                    {
                        File.Delete(fileFullPath);
                    }

                    File.Delete(fileFullPath);
                }
            }
            catch (Exception ex)
            {
                LogFileHelper.ERR("FileHelper", "DeleteFile", $"删除文件发生异常:{ex.Message}", ex);
            }
        }

        public static bool CheckFileIsIsExist(string fileUrl)
        {
            if (File.Exists(fileUrl))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="URL">文件网络地址</param>
        /// <param name="dir">下载文件夹地址</param>
        /// <param name="filename">下载文件名称</param>
        /// <param name="tryNum">重试次数</param>
        /// <returns></returns>
        public static string Download(string URL, string filename, int scriptId, int tryNum)
        {
            var dir = Path.Combine(ConfigExtensionsHelper.app("AudioFolderPath"), scriptId.ToString());
            var filePath = Path.Combine(dir, filename);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            bool isDownloaded = false;
            int downloadCount = 0;
            while (!isDownloaded && downloadCount < tryNum)
            {
                isDownloaded = Download($"{URL}", filePath);
                downloadCount++;
                if (!isDownloaded && downloadCount < tryNum - 1)
                {
                    Thread.Sleep(5000);
                }
            }
            return isDownloaded ? filePath : "";
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="URL">文件网络地址</param>
        /// <param name="dir">下载文件夹地址</param>
        /// <param name="filename">下载文件名称</param>
        /// <param name="tryNum">重试次数</param>
        /// <returns></returns>
        public static string Download(string dir, string URL, string filename, int tryNum)
        {
            var filePath = $"{dir}\\{filename}";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            bool isDownloaded = false;
            int downloadCount = 0;
            while (!isDownloaded && downloadCount < tryNum)
            {
                isDownloaded = Download($"{URL}", filePath);
                downloadCount++;
                if (!isDownloaded && downloadCount < tryNum - 1)
                {
                    Thread.Sleep(5000);
                }
            }
            return isDownloaded ? filePath : "";
        }

        /// <summary>
        /// 下载线上文件到本地
        /// </summary>
        /// <param name="URL">下载文件链接</param>
        /// <param name="filename">保存到本地的地址</param>
        /// <returns></returns>
        private static bool Download(string URL, string filename)
        {
            var isTrue = true;
            HttpWebRequest req = null;
            HttpWebResponse rep = null;
            Stream st = null;
            Stream so = null;
            try
            {
                req = (HttpWebRequest)WebRequest.CreateHttp(URL);//请求网络资源
                rep = (HttpWebResponse)req.GetResponse();//返回Internet资源的响应
                long totalBytes = rep.ContentLength;//获取请求返回内容的长度
                st = rep.GetResponseStream();//读取服务器的响应资源，以IO流的形式进行读写
                so = new FileStream(filename, FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (totalBytes > totalDownloadedByte)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);//读取当前字节流的总长度
                }
                so.Flush();
            }
            catch (Exception ex)
            {
                isTrue = false;
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (so != null) { so.Close(); so.Dispose(); }
                if (st != null) { st.Close(); st.Dispose(); }
                if (rep != null) { rep.Close(); rep.Dispose(); }
                if (req != null) { req.Abort(); }
            }

            return isTrue;
        }


        public static void Write(string path, string text)
        {
            try
            {
                File.AppendAllText(path, text);
            }
            catch (Exception)
            {

            }
        }

        public static string Read(string path)
        {
            return File.ReadAllText(path, Encoding.UTF8);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool Del(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }
    }
}
